/**
 * 病种入组病例管理初始化
 */
var SdsPatientList = {
    id: "patientListTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    hospID: null,
    checkPerm: "0", //$("#formCheck").val(), // 审核权限
    submitPerm: "1", //$("#formSubmit").val(), // 填报权限
    docUpPerm: $("#formCheckType").val(), // 医生能否直接上报配置
    enableIPQC: $("#enableIPQC").val(), // 是否启用过程质控
};

/**
 * 初始化表格的列
 */
SdsPatientList.initColumn = function () {
    var columnArr = [
        {
            title: '序号',
            width: 30,
            align: "center",
            valign: 'middle',
            sortable: true,
            formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize = $('#patientListTable').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber = $('#patientListTable').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {title: '科室', field: 'admLocDesc', width: 150, align: 'left', valign: 'middle'},
        {title: '病案号', field: 'mrNum', width: 80, align: 'left', valign: 'middle', formatter: function (value,row,index) {
                // 设置该列鼠标悬浮显示系统内就诊号，方便查找调试
                var span=document.createElement('span');
                span.setAttribute('title',row.id);
                span.innerHTML = value;
                return span.outerHTML;
            }},
        {title: '姓名', field: 'name', width: 80, align: 'left', valign: 'middle'},
        {title: '性别', field: 'sex', width: 30, align: 'center', valign: 'middle'},
        {title: '年龄', field: 'age', width: 30, align: 'center', valign: 'middle'},
        {title: '主管医生', field: 'admDocName', width: 80, align: 'left', valign: 'middle'},
        {title: '入院日期', field: 'admDate', width: 100, align: 'left', valign: 'middle'},
        {title: '出院日期', field: 'dishDate', width: 100, align: 'left', valign: 'middle'},
        {title: '在院质控病种', field: 'admEntityName', width: 140, align: 'left', valign: 'middle'},
        {title: '出院填报病种', field: 'entityName', width: 140, align: 'left', valign: 'middle',formatter: function (value, row, index) {
            if (row.state != 'O') {
                return value;
            }
            return '<span style="color: #cc0000">'+value+'(排除)</span>'
            }
        },
        {
            title: '操作',
            field: 'id',
            align: 'center',
            width: '60px',
            valign: 'middle',
            formatter: function (value, row, index) {
                var _html = '';
                if ($('#searchType').combobox('getValue') == "1") {
                    if (row.qcincaseId != "" && row.state != "O") {
                        //已入组
                        _html = '<a href="javascript:SdsPatientList.edit(\'' + row.id + '\',\'' + row.qcincaseId + '\',\'' + row.name + '\',\'' + row.mrNum + '\',\'' + row.dishDate + '\')" title="填报"><i class="hisui-icon icon-write-order"></i></a>';
                        _html += '<a href="javascript:SdsPatientList.del(\'' + row.qcincaseId + '\',\'' + row.entityId + '\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
                        // _html += '<a href="javascript:SdsPatientList.up(\''+row.qcincaseId+'\',\''+row.name+'\')" title="上报"><i class="hisui-icon icon-upload-cloud"></i></a>';
                    } else {
                        //未入组 和 已排除
                        _html = '<a href="javascript:SdsPatientList.inGroup(\'' + row.id + '\')" title="入组"><i class="hisui-icon icon-add-item"></i></a>';
                    }
                }
                return _html;
            }
        }];

    // 如果未启用过程质控模块，则不增加在院质控病种一列
    if ($('#enableIPQC').val() != "Y") {
        columnArr.splice(9,1);
    }

    return columnArr;
};

/**
 * 检查是否选中
 */
SdsPatientList.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        layer.msg("请先选中表格中的某一记录！");
        return false;
    } else {
        SdsPatientList.seItem = selected[0];
        return true;
    }
};

/**
 * 点击新增病种入组病例
 */
SdsPatientList.add = function () {
    var index = layer.open({
        type: 2,
        title: '新增病种入组病例',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        content: '/sds/sdsqcincase/to_add',
        cancel: function (index, layero) {
            layer.close(index);
            SdsPatientList.table.refresh();
            return false;
        }
    });
    this.layerIndex = index;
};

/**
 * 打开查看病种入组病例详情
 */
SdsPatientList.edit = function (episodeId, id, name, mrNum, dishDate) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        // 未启用过程质控模块直接打开填报表单
        if (SdsPatientList.enableIPQC == 'Y') {
            SdsPatientList.GetMrListIfo(episodeId, id, name, mrNum, dishDate);
        } else {
            SdsPatientList.openFormWin(id, name, mrNum, dishDate);
        }
    }
};

SdsPatientList.GetMrListIfo = function (episodeId, mrListId, name, mrNum, dishDate) {
    var mrlistInfo;
    var ajax = new $ax("/sds/sdsqcincase/getMrListInfo", function (data) {
        mrlistInfo = data;
    }, function () {
    });
    ajax.setData({"episodeId": episodeId});
    ajax.start();
    if (!$.isEmptyObject(mrlistInfo)) {
        var mrListId = mrlistInfo.mrlistIdOut;
        var entityIdOut = mrlistInfo.entityIdOut;
        var entityNameOut = mrlistInfo.entityNameOut;
        var entityIdIn = mrlistInfo.entityIdIn;
        var entityNameIn = mrlistInfo.entityNameIn;
        var tipsStr = "\t<p style='color:#ff7e00;background-color:#fff3dd;border: 1px solid #f7d199;text-indent:2em;'>该患者在院质控病种和出院入组筛查病种不一致，请选择并确认上报病种！</p>\n";
        tipsStr += "\t<div style='display: block;padding: 5px;'>\n"
        tipsStr += "\t<label>出院筛查病种：</label><input type=\"radio\" name=\"entityId\" value=\"" + entityIdOut + "\" checked>\n" + "<span style='color: #29723C'>" + entityNameOut + "</span>";
        tipsStr += "\t<br>\n";
        tipsStr += "\t<label>在院质控病种：</label><input type=\"radio\" name=\"entityId\" value=\"" + entityIdIn + "\">\n" + "<span style='color: #29723C'>" + entityNameIn + "</span>";
        tipsStr += "\t</div>\n";
        $("#mrListInfoHtml").html(tipsStr);
        var titleIndex = layer.open({
            type: 1,
            title: ['单病种填报提醒', 'padding-left:10px;background:#556983;color:white;'],
            content: $("#mrListInfoDiv"),
            area: ['350px', '250px'], //宽高
            fix: false, //不固定
            maxmin: false,
            skin: 'layer-ext-hisui',
            zIndex: 1100,
            btn: ['确定'],
            btnAlign: 'c',
            yes: function (index, layero) {
                layer.close(titleIndex);
                $.messager.progress({title: "提示", msg: '变更病种并自动采集填报数据', text: '采集中....'});
                SdsPatientList.changeMrEntity(mrListId, $('input[name="entityId"]:checked').val());
                $.messager.progress('close');
                SdsPatientList.openFormWin(mrListId, name, mrNum, dishDate);
            }
        });
    } else {
        SdsPatientList.openFormWin(mrListId, name, mrNum, dishDate)
    }
};

SdsPatientList.changeMrEntity = function (mrListId, entityId) {
    var ajax = new $ax("/sds/sdsqcincase/changeMrEntity", function (data) {
    }, function (data) {
    });
    ajax.setData({"mrListId": mrListId, "entityId": entityId});
    ajax.start();
};

// 打开表单填报窗口
SdsPatientList.openFormWin = function (mrListId, name, mrNum, dishDate) {
    var titleTips = "姓名:" + name + "|" + "病案号:" + mrNum + "|" + "出院日期:" + dishDate;
    var index = layer.open({
        type: 2,
        title: titleTips,
        area: ['1100px', '600px'], //宽高
        fix: false, //不固定
        content: '/sds/sdsqcformshow?mrListId=' + mrListId + '&execUser=' + encodeURIComponent($("#userName").val()) + '&checkPerm=' + SdsPatientList.checkPerm+'&submitPerm=' + SdsPatientList.submitPerm,
        cancel: function (index, layero) {
            layer.close(index);
            SdsPatientList.table.refresh();
            return false;
        }
    });
    this.layerIndex = index;
}

/**
 * 删除病种入组病例
 */
SdsPatientList.del = function (id, entityId) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        entityId = this.seItem.entityId;
        flag = true;
    }
    if (flag) {
        //打开 弹出框
        var index = layer.open({
            type: 2,
            title: ['排除单病种【信息录入】'],
            area: ['600px', '400px'],
            zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
            content: "/sds/sdsqcformshow/excludereason?mrListId=" + id + "&entityId=" + entityId + "&execUser=" + encodeURIComponent($("#userName").val()),
            skin: 'layer-ext-hisui',
            scrollbar: false//为了禁止父页面滚动条滚动
        });
        this.layerIndex = index;

        //监听子页面的postMessage
        function receiveMessage(event) {
            //取得子页面传回来的值
            if (event.data == "close") {
                // 如果传回close，关闭当前弹窗
                layer.close(index);
            }
            if (event.data == "save") {
                SdsPatientList.table.search();
                setTimeout(function () {
                    layer.close(index);
                }, 1000);
            }
        }

        if (window.addEventListener) {
            // 在现代浏览器中使用addEventListener
            window.addEventListener('message', receiveMessage, false);
        } else if (window.attachEvent) {
            // 在IE8及以下版本中使用attachEvent
            window.attachEvent('onmessage', receiveMessage);
        }
    }
};

/**
 * 点击上报病种
 */
SdsPatientList.up = function (id, name) {
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var ajax = new $ax("/sds/sdsqcformshow/upload/" + id, function (UpRet) {
        $.messager.progress("close");
        if (UpRet.code == 1) {
            $.messager.popover({msg: '上传成功！', type: 'success', timeout: 1000})
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '状态更新成功！', type: 'success', timeout: 1000})
                SdsPatientList.table.search();
            }, function (data) {
                $.messager.alert("错误提示", "状态更新错误!", 'info');
            });
            // 如果返回信息Code为“1”，且无message信息，则说明前置机该病种为测试状态，将该入组记录加个测试上报标识
            // if (UpRet.message == null || UpRet.message == "") {
            //     ax.set('testFlg', 1);
            // }
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.start();
        } else if (UpRet.message.indexOf('重复') > -1) {
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '已存在上传记录，状态更新成功！', type: 'success', timeout: 1000})
                SdsPatientList.table.search();
            }, function (data) {
                $.messager.alert("错误提示", "已存在上传记录，状态更新错误!", 'info');
            });
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.set('execUser', $("#userName").val());
            ax.set('reason', '');
            ax.set('resume', '');
            ax.start();
        } else {
            $.messager.alert("错误提示", "表单上传失败!Error=" + UpRet.message, 'info');
        }
    }, function (data) {
        $.messager.alert("错误提示", "表单上传失败!", 'info');
    });
    ajax.setAsync();
    ajax.start();
};

/**
 * 入组
 */
SdsPatientList.inGroup = function (id) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = layer.open({
            type: 2,
            title: '入单病种管理',
            area: ['600px', '400px'], //宽高
            fix: false, //不固定
            content: '/sds/sdsmedicalgroup/in_group/' + id,
            cancel: function (index, layero) {
                layer.close(index);
                SdsPatientList.table.refresh();
                return false;
            }
        });
        this.layerIndex = index;
    }
};

SdsPatientList.clear = function () {
    $("#name").val('');
    $("#admDoctorName").val('');
    $("#mrNum").val('');
    $("#dept").combobox("setValue", "");
    $("#formStatus").combobox("setValue", "");
    $("#entityId").combobox("setValue", "");
}

SdsPatientList.search = function () {
    var queryData = {};
    var searchType = $('#searchType').combobox('getValue');
    var startDate = $('#startDate').datebox('getValue');//开始日期
    var endDate = $('#endDate').datebox('getValue');//结束日期
    startDate = startDate + " 00:00:00";
    endDate = endDate + " 23:59:59";
    var dateType = "2";
    if (searchType == "2") {
        dateType = "1";
    }
    queryData['dateType'] = dateType;
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['mrNum'] = $("#mrNum").val();
    queryData['name'] = $("#name").val();
    queryData['admDoctorName'] = $("#admDoctorName").val();
    queryData['admLocId'] = $('#depart').val();
    queryData['admDocId'] = $("#userId").val();
    queryData['formStatus'] = $('#formStatus').combobox('getValue');
    queryData['entityId'] = $('#entityId').combobox('getValue');
    queryData['paDocDepart'] = $("[name='paDocDepart']:checked").val();
    queryData['searchType'] = searchType;
    SdsPatientList.table.refresh({query: queryData, pageNumber: 1});
};


$(function () {
    var dateType = "2";
    $("#entityId").combobox({
        url: "/sds/common/entityList",
        mode:'remote',
        valueField:'value',
        textField:'text',
        allowNull: true
    });

    //默认一星期
    $('#startDate').datebox('setValue', timeStamp2String(new Date().getTime() - (1000 * 60 * 60 * 24 * 7)));
    $('#endDate').datebox('setValue', timeStamp2String(new Date().getTime()));

    var searchType = $('#searchType').combobox('getValue');
    var startDate = $('#startDate').datebox('getValue');//开始日期
    var endDate = $('#endDate').datebox('getValue');//结束日期
    startDate = startDate + " 00:00:00";
    endDate = endDate + " 23:59:59";

    var dept = $('#depart').val();

    var defaultColunms = SdsPatientList.initColumn();
    var table = new BSTable(SdsPatientList.id, "/sds/sdsmedicalgroup/list", defaultColunms);
    table.setPaginationType("server");
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setShowToggle(false);
    table.setShowExport(false);
    table.setPageSize(15);
    /*table.setFixedColumns(true);//是否固定列
    table.setFixedNumber(4);//固定前几列*/
    table.setSubHeight(-27);
    var b_height = document.documentElement.clientHeight;
    table.set("dateType", dateType);
    table.set("startDate", startDate);
    table.set("endDate", endDate);
    table.set("admLocId", dept);
    table.set("searchType", searchType);
    SdsPatientList.table = table.init();
});

//在Jquery里格式化Date日期时间数据
function timeStamp2String(time) {
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}